import { _decorator, Component, EventKeyboard, Input, input, instantiate, KeyCode, Label, Layout, Node, Prefab, profiler, resources, Sprite, SpriteFrame, UITransform } from 'cc';
import { Weapon } from './Weapon';
const { ccclass, property } = _decorator;

@ccclass('Backpack')
export class Backpack extends Component {

    @property(Node)
    backpack: Node = null!                      // backpack

    @property(Node)
    backpackCover: Node = null!                 // 罩在Backpack上的一个节点，大小和位置和Backpack节点一样

    @property(Node)
    box: Node = null!                           // 箱子

    @property(Node)
    boxCover: Node = null!                      // 罩在box上的一个节点，大小和位置和box节点一样

    @property(Node)
    weaponLayoutNode: Node = null!              // 武器布局节点

    @property(Prefab)
    weaponItemPrefab: Prefab = null!            // 武器预制

    @property(Node)
    gridItem: Node = null;

    private weaponItemComArr = []

    start() {
        // profiler.hideStats()
        this.initGrid();
        this.addEvent(true);
    }

    protected onDestroy(): void {
        this.addEvent(false)
    }

    private addEvent(bAdd: boolean = true) {
        input[bAdd ? "on" : "off"](Input.EventType.KEY_DOWN, this.onKeydown, this)
    }

    private onKeydown(evt: EventKeyboard) {
        console.log(evt)
        switch (evt.keyCode) {
            case KeyCode.SPACE:
                this.rotateWeapon();
                break;
        }
    }

    private rotateWeapon(): void {
        for (let i = 0; i < this.weaponItemComArr.length; i++) {
            let weaponItem = this.weaponItemComArr[i]
            if (weaponItem.selected == true) {
                weaponItem.rotateWeapon()
            }
            weaponItem = null
        }
    }

    public addRandomWeapon(): void {
        let _self = this;
        resources.loadDir('weapon', SpriteFrame, function (err, assets) {
            let ridx = Math.floor(Math.random() * assets.length)
            let weaponItem = instantiate(_self.weaponItemPrefab)
            weaponItem.name = assets[ridx].name
            weaponItem.getComponent(Sprite).spriteFrame = assets[ridx]
            _self.weaponItemComArr.push(weaponItem.getComponent(Weapon))
            _self.weaponLayoutNode.addChild(weaponItem)
        })
    }

    private initGrid(): void {
        let rcNum = 5;
        let backPackLayout = this.backpack.getComponent(Layout);
        backPackLayout.constraint = Layout.Constraint.FIXED_COL;
        backPackLayout.constraintNum = rcNum;
        backPackLayout = null

        let boxLayout = this.box.getComponent(Layout);
        boxLayout.constraint = Layout.Constraint.FIXED_COL;
        boxLayout.constraintNum = rcNum;
        boxLayout = null

        let _self = this;
        this.loadByFrames("back", this.backpack, rcNum, () => {
            _self.initBackpackCover()

        })
        this.loadByFrames("box", this.box, rcNum, () => {
            _self.initBoxCover()
        })
        this.initWeaponLayout()
    }

    /**
     * 分帧加载
     */
    protected loadByFrames(name: string, node: Node, rcNum: number, finishCb: Function = null) {
        const total = rcNum * rcNum,
            countPerFrame = 5; // 每帧加载的数量
        let index = 0;  // 当前下标
        // 加载函数
        const load = () => {
            // 加载 item
            const count = Math.min(total - index, countPerFrame);
            for (let i = 0; i < count; i++) {
                this.addItem(node, `${name}${index}`);
                index++;
            }
            // 是否还有
            if (index < total) {
                // 下一帧继续加载
                this.scheduleOnce(() => load());
            } else {
                // console.log("统计times  loadByFrames--------->", new Date().valueOf());
                if (finishCb) {
                    finishCb();
                    finishCb = null
                }
            }
        };
        // 开始加载
        load();
    }

    private addItem(node: Node, name: string): void {
        let layout = node.getComponent(Layout);
        let item = instantiate(this.gridItem)
        item.getChildByName("lblGridName").getComponent(Label).string = item.name = name
        item.active = true;
        layout.node.addChild(item)
        layout = null;
        item = null;
    }

    /** 
     * @zh
     * 初始化Backpack Cover节点，该节点大小和位置永远要和Backpack节点一样。武器其实是放置在该节点上的。
    */
    initBackpackCover() {
        // 位置和Backpack节点一样
        let layout = this.backpack.getComponent(Layout);
        layout.updateLayout();
        layout = null
        this.backpackCover.setPosition(this.backpack.position)

        // 大小和Backpack节点一样
        let backpackUITransform = this.node.getComponent(UITransform)
        let backpackCoverUITransform = this.backpackCover.getComponent(UITransform)
        backpackCoverUITransform.setContentSize(backpackUITransform.width, backpackUITransform.height)
    }

    /** 
    * @zh
    * 初始化Box Cover节点，该节点大小和位置永远要和Box节点一样。武器其实是放置在该节点上的。
   */
    initBoxCover(): void {
        // 位置和Box节点一样
        let layout = this.box.getComponent(Layout);
        layout.updateLayout();
        layout = null
        this.boxCover.setPosition(this.box.position)

        // 大小和box节点一样
        let boxUITransform = this.node.getComponent(UITransform)
        let boxCoverUITransform = this.boxCover.getComponent(UITransform)
        boxCoverUITransform.setContentSize(boxUITransform.width, boxUITransform.height)
    }

    /** 
     * @zh
     * 将各个武器图片从resources/weapon文件夹中动态加载出来，并将武器节点放在Weapon Layout节点中。
    */
    initWeaponLayout() {
        let self = this
        this.weaponItemComArr = []
        let _self = this
        resources.loadDir('weapon', SpriteFrame, function (err, assets) {
            for (let i = 0; i < assets.length; i++) {
                let weaponItem = instantiate(self.weaponItemPrefab)
                weaponItem.name = assets[i].name
                weaponItem.getComponent(Sprite).spriteFrame = assets[i]
                _self.weaponItemComArr.push(weaponItem.getComponent(Weapon))
                self.weaponLayoutNode.addChild(weaponItem)
            }
        })
    }
}


